'use client'

import React, { useEffect, useState } from "react";
import {
    Button,
    Card,
    CardBody,
    CardHeader,
    Chip,
    Divider,
    Input,
    Modal,
    ModalBody,
    ModalContent,
    ModalFooter,
    ModalHeader,
    Spinner,
    Table,
    TableBody,
    TableCell,
    TableColumn,
    TableHeader,
    TableRow,
    Tooltip,
    useDisclosure
} from "@nextui-org/react";
import { BiArrowBack, BiEdit, BiPlus, BiTag, BiTrash } from "react-icons/bi";
import { useTags, TagItem } from "@/app/pages/profile/TagManagement";
import { useRouter } from "next/navigation";
import ToastUtil from "@/app/utils/toastUtil";
import { AuthenticationChecker } from "@/app/config/authenticationChecker";

export default function TagsPage() {
    const router = useRouter();
    const [isLoggedIn, setIsLoggedIn] = useState(false);
    const [loading, setLoading] = useState(true);
    const [tags, setTags] = useState<TagItem[]>([]);
    const [loadingText, setLoadingText] = useState("加载中...");
    const [currentPage, setCurrentPage] = useState(1);
    const [totalTags, setTotalTags] = useState(0);
    const pageSize = 20;
    
    // 使用标签钩子
    const { getUserTags, createTag, updateTag, deleteTag } = useTags();
    
    // Modal states
    const {isOpen: isOpenCreate, onOpen: onOpenCreate, onOpenChange: onOpenChangeCreate} = useDisclosure();
    const {isOpen: isOpenEdit, onOpen: onOpenEdit, onOpenChange: onOpenChangeEdit} = useDisclosure();
    const {isOpen: isOpenDelete, onOpen: onOpenDelete, onOpenChange: onOpenChangeDelete} = useDisclosure();
    
    // Form states
    const [newTagName, setNewTagName] = useState("");
    const [editTagId, setEditTagId] = useState<number | null>(null);
    const [editTagName, setEditTagName] = useState("");
    const [deleteTagId, setDeleteTagId] = useState<number | null>(null);
    const [deleting, setDeleting] = useState(false);
    const [submitting, setSubmitting] = useState(false);

    // Check authentication on load
    useEffect(() => {
        async function checkAuth() {
            setLoading(true);
            const [authenticated, username] = AuthenticationChecker();
            setIsLoggedIn(authenticated);
            
            if (!authenticated) {
                setLoadingText("请先登录");
                setTimeout(() => {
                    router.push('/');
                }, 1500);
            } else {
                await loadTags();
            }
            setLoading(false);
        }
        
        checkAuth();
    }, []);

    // Load tags from server
    const loadTags = async () => {
        setLoading(true);
        const tagsData = await getUserTags(currentPage, pageSize);
        
        if (tagsData) {
            setTags(tagsData.records);
            setTotalTags(tagsData.total);
        } else {
            setTags([]);
            setTotalTags(0);
        }
        
        setLoading(false);
    };

    // Handle pagination change
    useEffect(() => {
        if (isLoggedIn) {
            loadTags();
        }
    }, [currentPage, isLoggedIn]);

    // Create new tag
    const handleCreateTag = async () => {
        if (!newTagName.trim()) {
            ToastUtil("标签名称不能为空", "❌", "error");
            return;
        }
        
        setSubmitting(true);
        const success = await createTag(newTagName);
        
        if (success) {
            setNewTagName("");
            onOpenChangeCreate(false);
            loadTags();
        }
        
        setSubmitting(false);
    };

    // Edit tag
    const handleEditTag = async () => {
        if (!editTagId || !editTagName.trim()) {
            ToastUtil("标签名称不能为空", "❌", "error");
            return;
        }
        
        setSubmitting(true);
        const success = await updateTag(editTagId, editTagName);
        
        if (success) {
            setEditTagId(null);
            setEditTagName("");
            onOpenChangeEdit(false);
            loadTags();
        }
        
        setSubmitting(false);
    };

    // Delete tag
    const handleDeleteTag = async () => {
        if (!deleteTagId) return;
        
        setDeleting(true);
        const success = await deleteTag(deleteTagId);
        
        if (success) {
            setDeleteTagId(null);
            onOpenChangeDelete(false);
            loadTags();
        }
        
        setDeleting(false);
    };

    // Open edit modal
    const openEditModal = (tag: TagItem) => {
        setEditTagId(tag.id);
        setEditTagName(tag.name);
        onOpenEdit();
    };

    // Open delete modal
    const openDeleteModal = (tagId: number) => {
        setDeleteTagId(tagId);
        onOpenDelete();
    };

    // Create modal
    const createModal = (
        <Modal 
            isOpen={isOpenCreate} 
            onOpenChange={onOpenChangeCreate}
            backdrop="blur"
            placement="center"
            size="sm"
        >
            <ModalContent>
                {(onClose) => (
                    <>
                        <ModalHeader className="flex flex-col gap-1 text-center">
                            创建新标签
                        </ModalHeader>
                        <ModalBody>
                            <Input
                                autoFocus
                                label="标签名称"
                                placeholder="输入标签名称"
                                variant="bordered"
                                value={newTagName}
                                onValueChange={setNewTagName}
                                startContent={<BiTag className="text-default-400" />}
                            />
                        </ModalBody>
                        <ModalFooter className="justify-center">
                            <Button color="default" variant="flat" onPress={onClose} disabled={submitting}>
                                取消
                            </Button>
                            <Button color="primary" onPress={handleCreateTag} isLoading={submitting}>
                                创建
                            </Button>
                        </ModalFooter>
                    </>
                )}
            </ModalContent>
        </Modal>
    );

    // Edit modal
    const editModal = (
        <Modal 
            isOpen={isOpenEdit} 
            onOpenChange={onOpenChangeEdit}
            backdrop="blur"
            placement="center"
            size="sm"
        >
            <ModalContent>
                {(onClose) => (
                    <>
                        <ModalHeader className="flex flex-col gap-1 text-center">
                            编辑标签
                        </ModalHeader>
                        <ModalBody>
                            <Input
                                autoFocus
                                label="标签名称"
                                placeholder="输入新的标签名称"
                                variant="bordered"
                                value={editTagName}
                                onValueChange={setEditTagName}
                                startContent={<BiTag className="text-default-400" />}
                            />
                        </ModalBody>
                        <ModalFooter className="justify-center">
                            <Button color="default" variant="flat" onPress={onClose} disabled={submitting}>
                                取消
                            </Button>
                            <Button color="primary" onPress={handleEditTag} isLoading={submitting}>
                                保存
                            </Button>
                        </ModalFooter>
                    </>
                )}
            </ModalContent>
        </Modal>
    );

    // Delete modal
    const deleteModal = (
        <Modal 
            isOpen={isOpenDelete} 
            onOpenChange={onOpenChangeDelete}
            backdrop="blur"
            placement="center"
            size="sm"
        >
            <ModalContent>
                {(onClose) => (
                    <>
                        <ModalHeader className="flex flex-col gap-1 text-center">
                            删除标签
                        </ModalHeader>
                        <ModalBody>
                            <p className="text-center">确定要删除这个标签吗？此操作不可撤销。</p>
                        </ModalBody>
                        <ModalFooter className="justify-center">
                            <Button color="default" variant="flat" onPress={onClose} disabled={deleting}>
                                取消
                            </Button>
                            <Button color="danger" onPress={handleDeleteTag} isLoading={deleting}>
                                删除
                            </Button>
                        </ModalFooter>
                    </>
                )}
            </ModalContent>
        </Modal>
    );

    // Render loading state
    if (loading) {
        return (
            <div className="flex h-screen items-center justify-center bg-white dark:bg-default-100">
                <div className="text-center">
                    <Spinner size="lg" color="primary" />
                    <p className="mt-2 text-gray-500">{loadingText}</p>
                </div>
            </div>
        );
    }

    return (
        <div className="min-h-screen bg-white dark:bg-default-100 p-4">
            <div className="max-w-6xl mx-auto">
                {/* Header */}
                <div className="flex items-center justify-between mb-6">
                    <div className="flex items-center">
                        <Button 
                            isIconOnly 
                            variant="light" 
                            className="mr-2"
                            onClick={() => router.push('/')}
                        >
                            <BiArrowBack className="text-xl" />
                        </Button>
                        <h1 className="text-2xl font-bold">标签管理</h1>
                    </div>
                    <Button 
                        color="primary" 
                        endContent={<BiPlus />}
                        onPress={onOpenCreate}
                    >
                        新建标签
                    </Button>
                </div>

                {/* Main Content */}
                <Card shadow="sm" className="mb-6">
                    <CardHeader className="flex justify-between">
                        <h2 className="text-lg font-semibold">我的标签</h2>
                        <Chip variant="flat" color="primary">{totalTags} 个标签</Chip>
                    </CardHeader>
                    <Divider />
                    <CardBody>
                        {tags.length === 0 ? (
                            <div className="flex flex-col items-center justify-center p-10">
                                <BiTag className="text-6xl text-gray-300 mb-4" />
                                <p className="text-gray-500 mb-6">您还没有创建任何标签</p>
                                <Button 
                                    color="primary" 
                                    variant="flat" 
                                    endContent={<BiPlus />}
                                    onPress={onOpenCreate}
                                >
                                    创建第一个标签
                                </Button>
                            </div>
                        ) : (
                            <div className="overflow-x-auto">
                                <Table aria-label="标签列表" removeWrapper>
                                    <TableHeader>
                                        <TableColumn>标签名称</TableColumn>
                                        <TableColumn>创建时间</TableColumn>
                                        <TableColumn>最后更新</TableColumn>
                                        <TableColumn width={120} className="text-center">操作</TableColumn>
                                    </TableHeader>
                                    <TableBody>
                                        {tags.map((tag) => (
                                            <TableRow key={tag.id}>
                                                <TableCell>
                                                    <div className="flex items-center">
                                                        <BiTag className="mr-2 text-primary" />
                                                        {tag.name}
                                                    </div>
                                                </TableCell>
                                                <TableCell>{new Date(tag.createdAt).toLocaleString()}</TableCell>
                                                <TableCell>{new Date(tag.updatedAt).toLocaleString()}</TableCell>
                                                <TableCell>
                                                    <div className="flex justify-center gap-2">
                                                        <Tooltip content="编辑标签">
                                                            <Button 
                                                                isIconOnly 
                                                                size="sm" 
                                                                variant="light"
                                                                onPress={() => openEditModal(tag)}
                                                            >
                                                                <BiEdit className="text-blue-500" />
                                                            </Button>
                                                        </Tooltip>
                                                        <Tooltip content="删除标签">
                                                            <Button 
                                                                isIconOnly 
                                                                size="sm" 
                                                                variant="light"
                                                                onPress={() => openDeleteModal(tag.id)}
                                                            >
                                                                <BiTrash className="text-danger" />
                                                            </Button>
                                                        </Tooltip>
                                                    </div>
                                                </TableCell>
                                            </TableRow>
                                        ))}
                                    </TableBody>
                                </Table>
                            </div>
                        )}
                    </CardBody>
                </Card>

                {/* Pagination */}
                {totalTags > pageSize && (
                    <div className="flex justify-center mt-4">
                        <Button.Group>
                            <Button 
                                disabled={currentPage === 1}
                                onClick={() => setCurrentPage(currentPage - 1)}
                                variant="flat"
                            >
                                上一页
                            </Button>
                            <Button variant="flat" disabled>
                                {currentPage} / {Math.ceil(totalTags / pageSize)}
                            </Button>
                            <Button 
                                disabled={currentPage >= Math.ceil(totalTags / pageSize)}
                                onClick={() => setCurrentPage(currentPage + 1)}
                                variant="flat"
                            >
                                下一页
                            </Button>
                        </Button.Group>
                    </div>
                )}

                {/* Modals */}
                {createModal}
                {editModal}
                {deleteModal}
            </div>
        </div>
    );
} 